//
//  GHOAuthViewController.swift
//  GHWeibo
//
//  Created by LGH on 2017/8/20.
//  Copyright © 2017年 LGH. All rights reserved.
//

import UIKit
import SVProgressHUD

class GHOAuthViewController: UIViewController {

    lazy var webView = UIWebView()
    
    override func loadView() {
        
        setupUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.delegate = self
        webView.scrollView.isScrollEnabled = false
        loadRequest()
    }
    
    func setupUI() {
        
        view = webView
        webView.backgroundColor = UIColor.white
        navigationItem.leftBarButtonItem = UIBarButtonItem(titile: "返回", normalColor: UIColor.darkGray, higlightedColor: UIColor.orange, imageName: "navigationbar_back_withtext", highlightedImageName: "navigationbar_back_withtext_highlighted", target: self, action: #selector(back))
        navigationItem.title = "登录新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(titile: "自动填充", normalColor: UIColor.darkGray, higlightedColor: UIColor.orange, target: self, action: #selector(autoFill))
    }
    
    func loadRequest() {
        
        var urlString = "https://api.weibo.com/oauth2/authorize"
        let client_id = "client_id=\(GHAppKey)"
        let redirect_uri = "&redirect_uri=\(GHRedirectURI)"
        urlString = urlString + "?" + client_id + redirect_uri
        print(urlString)
        guard let url = URL(string: urlString) else{
            
            return
        }
        let request = URLRequest(url: url)
        webView.loadRequest(request)

    }
    
    func back() {
        
        dismiss(animated: true, completion: nil)
        SVProgressHUD.dismiss()
    }
    func autoFill() {
        
        let js = "document.getElementById('passwd').value= 'liuguanghai/*-';" + "document.getElementById('userId').value= '13166377659@sina.cn'"
        webView.stringByEvaluatingJavaScript(from: js)
    }

}

// MARK: - UIWebViewDelegate
extension GHOAuthViewController: UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //如果不包含，说明是微博的API，所以要加载
        if request.url?.absoluteString.hasPrefix(GHRedirectURI) == false {
            
            return true
            
        }else{
            
            if request.url?.query?.hasPrefix("code=") == true {
                print("获取授权码 = \(request.url?.query ?? "")")
                let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
                print("\(code)")
                GHNetworkManager.shared.getAccessToken(code: code)
                return false
            }else {
                
                print("取消授权")
                back()
                return false
            }
        }
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
